package org.spring.aicloud.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class ThreadPoolConfig {
    @Bean
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程数
        executor.setCorePoolSize(Runtime.getRuntime().availableProcessors()+1); // 默认CPU核心数+1
        //最大线程数
        executor.setMaxPoolSize(Runtime.getRuntime().availableProcessors()*2+1); //CPU核心数*2+1
        //任务队列
        executor.setQueueCapacity(10000);
        //临时线程的存活时间
        executor.setKeepAliveSeconds(60);
        //线程前缀
        executor.setThreadNamePrefix("thread-pool-");
        //执行自定义的拒绝策略
        executor.setRejectedExecutionHandler(new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                //todo:1保存拒绝的任务
                //todo:2通知相关的负责人进行手动处理
            }
        });
        //初始化对象
        executor.initialize();
        return executor;
    }
}
